//
//  MainViewController.m
//  budgetplan
//
//  Created by Barak on 10/26/12.
//  Copyright (c) 2012 Barak. All rights reserved.
//

#import "MainViewController.h"
#import "PQHttpRequest.h"
#import "LimitationRulesController.h"
#import "Account.h"
#import "PQHttpRequest.h"
#import "AppDelegate.h"
#import "CreditCardsController.h"
#import "Card.h"

@interface MainViewController ()

@end

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _budgetUtilizationBar = [[SectionsUtilizationBar alloc] init];
    _budgetUtilizationBar.frame = CGRectMake(30, 125, 260, 30);
    [self.view addSubview:_budgetUtilizationBar];
    
    [self displaySummery];
    [self displayAccountInformation:[Account mainAccount]];
	// Do any additional setup after loading the view.

}

- (void)displayAccountInformation:(Account *)account {
    _balanceLabel.text = [NSString stringWithFormat:@"%@€", account.actualBalance];
    _accountNumLabel.text = account.accountNumber;
    _accountNumLabel.text = [_accountNumLabel.text stringByReplacingOccurrencesOfString:@"null"
                                                     withString:@"0"];
}

static NSNumber *static_amount;
static NSNumber *static_category;

- (void) refreshFromServer {
    // get budget rules
    NSURL* budgetRulesUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@account_budget_rules.json?account_id=%@", OUR_SERVER_URL, [Account mainAccount].accountId]];
    
    [PQHttpRequest getJSONFromURL:budgetRulesUrl response:^(id response, NSError *error) {
        NSMutableArray* budgetRules = [[NSMutableArray alloc] init];
        NSArray* rules = [response objectForKey:@"categories"];
        for (NSDictionary* ruleValues in rules) {
            [budgetRules addObject:[BudgetRule instanceFromDictionary:ruleValues]];
        }
        
        [Account mainAccount].budgetRules = budgetRules;
        
        [self displaySummery];
    }];
    
    NSString* token = ((AppDelegate*)[[UIApplication sharedApplication] delegate]).apiToken;
    
    NSURL* accountURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@/operations/account/%@", BASE_URL, token, [Account mainAccount].accountId]];
    // get account data
    [PQHttpRequest getJSONFromURL:accountURL response:^(id accountResponse, NSError *error) {

        NSArray* cards = [Account mainAccount].cards;
        NSArray* budgetRules = [Account mainAccount].budgetRules;
        Account* account = [Account instanceFromDictionary:[accountResponse objectForKey:@"data"]];
        [Account mainAccount].budgetRules = budgetRules;

        
        if (cards && cards.count > 0){
            [Account mainAccount].cards = cards;
        }



        [self displayAccountInformation:account];
    }];
    /// IF-DEBUG ///
    ////////////////
    // STUB method for demo implamntation of push notifications (using pulling) as Apple are not fast enogh ib Dev env.
    // See application didFinishLaunchingWithOptions for real implamntation
    //////////////////////////////////////////////////////////
    NSURL* pushUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@notifications.json?account_id=%@", OUR_SERVER_URL, [Account mainAccount].accountId]];
    
    [PQHttpRequest getJSONFromURL:pushUrl response:^(id response, NSError *error) {
        //NSMutableArray* budgetRules = [[NSMutableArray alloc] init];
        if (response != nil)
        {
            NSString* account_id = [response objectForKey:@"account_id"];
            NSNumber* price = [response objectForKey:@"price"];
            NSNumber* amount = [response objectForKey:@"amount"];
            NSString* category_name = [response objectForKey:@"category_name"];
            static_amount = amount;
            static_category = [response objectForKey:@"category_id"];
            
            NSString* paymentMsg = [NSString stringWithFormat:@"Please approve payment of %@ € which exceeds  %@ budget by %@ €", price, category_name, amount];
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@""
                                                                message:paymentMsg
                                                               delegate:self
                                                      cancelButtonTitle:@"Decline"
                                                      otherButtonTitles:@"Approve", nil];
            
            alertView.alertViewStyle = UIAlertViewStyleDefault;
            
            [alertView show];
            
            
        }
    }];
    
    
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    NSLog(@"Alert View dismissed with button at index %d",buttonIndex);
    
    // Button pressed is approve
    if (buttonIndex != 0) {
        
        NSURL* pushUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@budget_exceptions?account_id=%@&amount=%@&category_id=%@", OUR_SERVER_URL, [Account mainAccount].accountId, static_amount, static_category]];
        
        [PQHttpRequest getJSONFromURL:pushUrl response:^(id response, NSError *error) {}];
    }
    
}

- (void) displaySummery {
    NSMutableArray* values = [[NSMutableArray alloc] init];
    NSNumber* totalBudget;
    for (BudgetRule* rule in [Account mainAccount].budgetRules) {
        if ([rule.category isEqualToString:@"Total budget"]) {
            totalBudget = rule.budgetLimit;
        } else {
            [values addObject:rule.utilization];
        }
    }
    _budgetUtilizationBar.total = [totalBudget doubleValue];
    
    //_budgetUtilizationBar.sectionsValues = @[@23, @14, @8, @11, @31];
    _budgetUtilizationBar.sectionsValues = values;
    [_budgetUtilizationBar update];
    
    [self performSelector:@selector(refreshFromServer) withObject:nil afterDelay:5];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"budgetPlan"]) {
        LimitationRulesController* budgetLimitsController = (LimitationRulesController*)segue.destinationViewController;
        budgetLimitsController.budgetrules = [Account mainAccount].budgetRules;
    }
    
    if ([segue.identifier isEqualToString:@"creditCards"]) {
        CreditCardsController* cardsController = (CreditCardsController*)segue.destinationViewController;
        cardsController.cards = [[NSMutableArray alloc] initWithArray:[Account mainAccount].cards];
    }
}

@end
